package com.wtwd.campus.receiver;

import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.annotation.MsgType;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.constant.SignConstant;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.fjryE15.untils.XyyUtiils;
import com.wtwd.campus.h5_manager.entity.DeviceLog;
import com.wtwd.campus.h5_manager.service.DeviceLogService;
import com.wtwd.campus.service.DeviceInfoService;
import com.wtwd.campus.service.IRMFeignClientService;
import com.wtwd.campus.service.WarningRecordService;
import com.wtwd.campus.service.WxService;
import com.wtwd.campus.utils.*;
import com.wtwd.campus.vcom.common.Constant;
import com.wtwd.campus.vcom.entity.VcomWarningRecord;
import com.wtwd.campus.vcom.service.VcomH5Service;
import com.wtwd.campus.vcom.utils.VcomPushUtils;
import com.wtwd.campus.wx.service.WxUtilsService;
import com.wtwd.campus.wx.utils.PushModel;
import com.wtwd.campus.wx.utils.WxUtils;
import org.apache.commons.lang.StringUtils;
import org.jeewx.api.core.req.model.message.TemplateMessageSendResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@MsgType(value = Constants.LOW_BATTERY_WARNING)
public class LowBatteryWarningReceiverHandler implements IReceiverHandler {

    @Value("${web.customerCode.xb}")
    private String xbCustomerCode;

    @Value("${web.customerCode.cw}")
    private String cwCustomerCode;

    @Value("${h5.customerId.ryh5}")
    private Integer ryh5CustomerId;

    @Value("${h5.customerId.hbDxRyh5}")
    private Integer hbDxRyh5CustomerId;

    @Value("${wx.general.push.customerCode}")
    private String wxPushCustomerCode;

    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private WarningRecordService warningRecordService;
    @Autowired
    private IRMFeignClientService irmFeignClientService;
    @Autowired
    private PushUtils pushUtils;
    @Autowired
    private ReceiverUtils receiverUtils;
    @Autowired
    private WxService wxService;
    @Autowired
    private VcomPushUtils vcomPushUtils;
    @Autowired
    private VcomH5Service vcomH5Service;
    @Autowired
    private DeviceLogService deviceLogService;
    @Autowired
    private WxUtilsService wxUtilsService;


    @Override
    public void handlerMessage(MqMessage mqMessage) {
        MqGeneralValueResult mqGeneralValueResult = (MqGeneralValueResult) mqMessage.getObject();
        String imei = mqGeneralValueResult.getImei();
        String commandNumber = mqGeneralValueResult.getCommandNumber();
        //处理指令回复的时间
        String deviceDate = mqGeneralValueResult.getDeviceDate();
        String deviceTime = mqGeneralValueResult.getDeviceTime();
        Long time = getTime(deviceDate, deviceTime);
        DeviceInfo deviceInfo = deviceInfoService.getDeviceByImei(imei);
        if (deviceInfo != null) {
            //修改设备信息
            deviceInfo.setLastUpTime((new Date()).getTime());
            deviceInfoService.modifyDeviceInfo(deviceInfo);
            if (deviceInfo.getDeviceType() == Constants.VCOM_DEVICE) {
                //存储威科姆的低电量告警
                List<String> studentIds = vcomH5Service.getStudentIdByImei(imei);
                if (studentIds != null && studentIds.size() > 0) {
                    for (String studentId : studentIds) {
                        VcomWarningRecord record = new VcomWarningRecord();
                        record.setType(Constant.WARNING_LOW_BATTERY);
                        record.setTime(time);
                        record.setImei(imei);
                        record.setStudentId("0");
                        if (!StringUtils.isBlank(studentId)) {
                            record.setStudentId(studentId);
                        }
                        vcomH5Service.addVcomWarningRecord(record);
                    }
                } else {
                    VcomWarningRecord record = new VcomWarningRecord();
                    record.setType(Constant.WARNING_LOW_BATTERY);
                    record.setTime(time);
                    record.setImei(imei);
                    record.setStudentId("0");
                    vcomH5Service.addVcomWarningRecord(record);
                }
            } else {
                //存储低电告警记录
                WarningRecord record = new WarningRecord();
                record.setDevice_id(deviceInfo.getDeviceId());
                record.setWarning_type(Constants.LOW_BATTERY_WARNING_TYPE);
                record.setWarning_time(time);
                record.setAddress(deviceInfo.getAddress());
                warningRecordService.addWarningRecord(record);
            }
            //进行指令回复
            irmFeignClientService.replyBLOW(imei, commandNumber);
            if (deviceInfo.getCustomerId() != null && deviceInfo.getDeviceType() == 2) {
                pushUtils.pushLowBatteryWarn(deviceInfo);
            } else if (deviceInfo.getDeviceType() == Constants.HXY_DEVICE) {
                Integer battery = deviceInfo.getBattery();
                if (battery == null || battery > 20) {
                    battery = 20;
                }
                pushUtils.pushHxyLowBattery(imei, DateUtils.format(new Date(), DateUtils.dateFormat4), battery);
            } else if (deviceInfo.getDeviceType() == Constants.VCOM_DEVICE) {
                // 推送威科姆
                vcomPushUtils.pushWarning(0, 0, "", 2, "电量低于15%", System.currentTimeMillis(), imei, "", "");
            } else if (deviceInfo.getDeviceType() == Constants.H5_DEVICE) {//针对H5客户进行推送
                if (deviceInfo.getCustomerId() == 5 || deviceInfo.getCustomerId() == 8) {
                    pushUtils.hnh5PushAlarmInfo(deviceInfo.getImei(), "电量低于15%", DateUtils.format(new Date(), DateUtils.dateFormat1), null, null, null);
                } else if (deviceInfo.getCustomerId() == ryh5CustomerId) {
                    BatteryReport batteryReport = new BatteryReport();
                    batteryReport.setImei(deviceInfo.getImei());
                    batteryReport.setBattery("15");
                    batteryReport.setReportTime(DateUtils.format(new Date(), DateUtils.dateFormat15));
                    XyyUtiils.pushBatteryReport(batteryReport);
                } else if (hbDxRyh5CustomerId.equals(deviceInfo.getCustomerId())) {
                    HbDxE15RyPushEntity hbDxE15RyPushEntity = new HbDxE15RyPushEntity();
                    hbDxE15RyPushEntity.setImei(deviceInfo.getImei());
                    hbDxE15RyPushEntity.setmType(HbDxE15RyPushEntity.PushTypeEnum.ALARM_TYPE.getType());
                    hbDxE15RyPushEntity.setmClass(HbDxE15RyPushEntity.MessageType.LOW_BATTERY_MESSAGE.getType());
                    hbDxE15RyPushEntity.setmTime(DateUtils.format(new Date(time), DateUtils.dateFormat4));
                    hbDxE15RyPushEntity.setMemo(MessageFormat.format(HbDxE15RyPushEntity.MessageType.LOW_BATTERY_MESSAGE.getTemplate(), deviceInfo.getImei()));
                    HbDxE15RyUtiils.hbDxE15RyPush(hbDxE15RyPushEntity);
                }
            }
            //如果是平台设备，推送到微信（不推瑞翼和喜马拉雅）
            if (!StringUtils.isBlank(deviceInfo.getOrgCode()) && !deviceInfo.getOrgCode().contains("A01A03A05") && !deviceInfo.getOrgCode().contains("A01A07") && !deviceInfo.getOrgCode().contains("A01A38")) {
                //根据学生id查询推送openID
                if (deviceInfo.getStudentId() != null) {
                    List<Map<String, Object>> openIdList = wxService.getOpenIdByStuId(deviceInfo.getStudentId());
                    openIdList.stream().forEach(e -> {
                        String stuName = (String) e.get("student_name");
                        String openId = (String) e.get("open_id");
                        if (!StringUtils.isBlank(openId)) {
                            String content = stuName.concat("的校园卡电量不足，请及时充电");
                            String tip = stuName.concat("的校园卡电量不足，请及时充电");
                            if (!StringUtils.isBlank(openId)) {
                                //创维推送创维,平台推送平台
                                if (deviceInfo.getOrgCode().startsWith(cwCustomerCode)) {
                                    TemplateMessageSendResult sosRecordTemplate = PushModel.createWarningTemplateCW(stuName, time, content, tip);
                                    sosRecordTemplate.setTouser(openId);
                                    WxUtils.pushMsgCW(sosRecordTemplate);
                                } else if (deviceInfo.getOrgCode().startsWith(xbCustomerCode)) {
                                    TemplateMessageSendResult sosRecordTemplate = PushModel.createWarningTemplateXB(stuName, time, content, tip);
                                    sosRecordTemplate.setTouser(openId);
                                    WxUtils.pushMsgXB(sosRecordTemplate);
                                } else {
                                    String pushCode = "";
                                    if (StringUtils.isNotBlank(wxPushCustomerCode) && StringUtils.isNotBlank(deviceInfo.getOrgCode())) {
                                        List<String> customerCodeString = Arrays.asList(wxPushCustomerCode.split(SignConstant.COMMA));
                                        pushCode = wxUtilsService.getWxCustomerCode(customerCodeString, deviceInfo.getOrgCode());
                                        if (StringUtils.isNotBlank(pushCode)) {
                                            TemplateMessageSendResult warningTemplate = wxUtilsService.createWarningTemplate(pushCode, imei, stuName, time, content, tip);
                                            warningTemplate.setTouser(openId);
                                            wxUtilsService.pushMsg(pushCode, warningTemplate);
                                        }
                                    }
                                    if (StringUtils.isBlank(pushCode)) {
                                        TemplateMessageSendResult sosRecordTemplate = PushModel.createWarningTemplate(stuName, time, content, tip);
                                        sosRecordTemplate.setUrl("");
                                        sosRecordTemplate.setTouser(openId);
                                        WxUtils.pushMsg(sosRecordTemplate);
                                    }
                                }
                            }
                        }
                    });
                }
            }
            //存储设备接收日志
            DeviceLog deviceLog = new DeviceLog();
            deviceLog.setSendUser(Constants.DEVICE_USER);
            deviceLog.setImei(imei);
            deviceLog.setBigType(Constants.LOW_BATTERY_WARNING);
            JSONObject contant = new JSONObject();
            contant.put("设备号", imei);
            contant.put("日期", deviceDate);
            contant.put("时间", deviceTime);
            deviceLog.setCmd(contant.toJSONString());
            deviceLog.setSendTime(System.currentTimeMillis());
            deviceLog.setCommandNumber(commandNumber);
            deviceLog.setState(1);
            deviceLogService.addDeviceLog(deviceLog);
        } else {
            saveUnInStorage(imei);
            receiverUtils.cloaseChannel(imei);
        }
    }


}
